package com.qf.service.Impl;/*
 * @Author: {{author}}
 * @Date:   {{create_time}}
 * @Last Modified by:   {{last_modified_by}}
 * @Last Modified time: {{last_modified_time}}
 */

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.mapper.TbUserMapper;
import com.qf.model.TbUser;
import com.qf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<TbUserMapper,TbUser> implements UserDetailsService,UserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //连接数据库
        //条件查询
        LambdaQueryWrapper<TbUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(TbUser::getUsername,username);
        TbUser tbUser = getOne(lambdaQueryWrapper);
        System.out.println(tbUser);
        if (tbUser!=null){

            //需要去数据库查询 角色  权限等数据
            // GrantedAuthority  代表角色和权限
            List<GrantedAuthority> list = new ArrayList<>();
            System.out.println(list);
            if ("zhangsan".equals(tbUser.getUsername())){
                //凡是角色 必须添加  ROLE_
                list.add(new SimpleGrantedAuthority("ROLE_student"));
                list.add(new SimpleGrantedAuthority("ROLE_admin"));
            }else if ("ww".equals(tbUser.getUsername())){
                list.add(new SimpleGrantedAuthority("update"));  //凡是不是ROLE开头的就是权限
            }else {
                list.add(new SimpleGrantedAuthority("ROLE_teacher"));
            }
            return new User(username, tbUser.getPassword(),list);
        }

      /*  if ("steel".equals(username)) {
            String encode = passwordEncoder.encode("123456");
            List<GrantedAuthority> list = new ArrayList<>();

            return new User(username, encode,list);

        }*/
        System.out.println("用户名不存在");
        return null;

    }
}
